﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;

namespace TV4Home.Client.WMC.TVClient.UI
{
    /// <summary>
    /// This class provides static functions for sending pings to target computers.
    /// </summary>
    public static class PingHelper
    {
        #region Private Fields
        // create a new Ping-object for use by the static functions
        private static readonly Ping pingSender = new Ping();
        #endregion

        #region Public Methods
        /// <summary>
        /// Pings a target machine.
        /// </summary>
        /// <param name="address">The address of the target machine.</param>
        /// <param name="timeout">The timeout in milliseconds.</param>
        /// <returns>A boolean indicating if the ping was successful.</returns>
        public static bool SinglePingTarget(string address, int timeout)
        {
            PingReply reply;

            // send a ping and get the reply
            try { reply = pingSender.Send(address, timeout); }
            catch { return false; }

            // if the ping was successful, return true; otherwise false
            if (reply != null && reply.Status == IPStatus.Success)
                return true;
            else
                return false;
        }

        /// <summary>
        /// Pings a target machine and returns a value if the connection was successful.
        /// </summary>
        /// <param name="address">The address of the target machine.</param>
        /// <param name="numberOfPings">The number of pings.</param>
        /// <param name="timeout">The timeout in milliseconds for one ping.</param>
        /// <returns>A boolean indicating if more pings were successful than failed.</returns>
        public static bool PingTarget(string address, int numberOfPings, int timeout)
        {
            // local variables for counting sucessful and failed pings
            int successCount = 0, failCount = 0;

            // loop according to the number of pings the user wants to send
            for (int i = 0; i < numberOfPings; i++)
            {
                // Ping the target machine and increment variables according to the result
                if (SinglePingTarget(address, timeout))
                    successCount++;
                else
                    failCount++;
            }

            // if there were more successful pings than failed ones, return true; otherwise false
            return successCount > failCount;
        }
        #endregion
    }
}
